﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <div class="w25pr30">
                    <el-form-item label-width="120px" label="要货时间" prop="applyDate">
                        <el-date-picker
                            v-model="entityObj.applyDate"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入要货时间"
                            style="width: 100%;margin-left: 9px;"
                        />
                    </el-form-item>
                </div>
                <div class="w25pr30">
                    <el-form-item label-width="120px" label="期望到货时间">
                        <el-date-picker
                            v-model="entityObj.expectedDate"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入要货时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </div>
                <div class="w25">
                    <el-form-item label-width="120px" label="供货单位" prop="purchaseUnityId">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{ entityObj.purchaseRealName }}
                                <br />
                                联系电话:{{ entityObj.purchaseMobile }}
                                <br />
                                联系地址:{{ entityObj.purchaseAddress }}
                                <br />
                            </template>
                            <el-input
                                disabled
                                v-model="entityObj.purchaseUnityName"
                                style="width: 100%"
                            />
                        </el-tooltip>
                    </el-form-item>
                </div>
            </el-row>
            <el-row>
                <el-col :span="12" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="要货清单" prop="applyOrderItems">
                        <div @click="addMaterial()" class="add-material-but">新增物料</div>
                        <div @click="addApplyOrder()" class="add-order-but">从历史要货记录中复购</div>
                        <!-- <el-button @click="addMaterial()"  size="small">新增物料</el-button> -->
                        <!-- <el-button size="small" @click="addApplyOrder()" style="margin-left: 20px;">从历史要货记录中复购</el-button> -->
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="110px">
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="物料编号" label-width="80px">
                                <el-input
                                    placeholder="---请输入编号---"
                                    v-model="queryList.materialCode"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料名称" label-width="80px">
                                <el-input
                                    placeholder="---请输入名称---"
                                    v-model="queryList.materialName"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料分类" label-width="80px">
                                <el-tree-select
                                    placeholder="---请选择物料分类---"
                                    v-model="queryList.materialTypeIds"
                                    :props="{ label: 'label', value: 'value', children: 'children' }"
                                    collapse-tags
                                    collapse-tags-tooltip
                                    :data="materialTypeTree"
                                    multiple
                                    :render-after-expand="false"
                                    show-checkbox
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-button
                                :icon="Search"
                                type="primary"
                                @click="handleSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                        </el-form>
                        <el-table :data="itemsData" border style="width: 100%" show-summary>
                            <el-table-column label="操作" min-width="160">
                                <template #default="scope">
                                    <el-button
                                        style="margin-right: 10px;"
                                        @click="deleteRow(scope.$index, scope.row)"
                                        class="del-temp-but"
                                    >移除</el-button>
                                    <el-button
                                        @click="opStoreRow(scope.$index, scope.row)"
                                        class="del-temp-but"
                                    >分配门店</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料编码" min-width="100">
                                <template #default="scope">{{scope.row.materialCode}}</template>
                            </el-table-column>
                            <el-table-column label="物料名称" min-width="150">
                                <template #default="scope">
                                    <template v-if="scope.row.applyOrderItemType == 0">
                                        <div
                                            v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                            style="color: #318cf2;"
                                            @click="handlePreview(scope.row)"
                                        >{{scope.row.materialName}}</div>
                                        <div v-else>{{scope.row.materialName}}</div>
                                    </template>
                                    <el-input v-else v-model="scope.row.materialName" />
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" min-width="110">
                                <template #default="scope">
                                    <template
                                        v-if="scope.row.applyOrderItemType == 0"
                                    >{{ scope.row.materialSpecs}}</template>
                                    <el-input v-else v-model="scope.row.materialSpecs" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="85">
                                <template #default="scope">{{ scope.row.unitName }}</template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="120" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        :min="scope.row.minQty"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="分配门店" min-width="160">
                                <template #default="scope">
                                    <el-popover placement="bottom-start" :width="800" trigger="click" v-if="scope.row?.purchases&&scope.row?.purchases?.length>0">
                                        <template #reference>
                                            <div style="position: relative;text-overflow: ellipsis;white-space: nowrap;cursor: pointer;display: block;color: #318cf3;">
                                                {{ scope.row.purchases.map((store) => `${store.storeName}/${store.qty}`).join(", ") }}
                                            </div>
                                        </template>
                                        <el-table :data="scope.row?.purchases" :style="scope.row?.purchases?.length>6?'height: 300px;width: 100%;':'width: 100%;'" stripe :row-class-name="setMaterialRowClass">
                                            <el-table-column prop="rowNumber" label="序号" width="60" >
                                                <template #default="storeScope">{{storeScope.$index+1}}</template>
                                            </el-table-column>
                                            <el-table-column prop="storeName" label="门店名称" min-width="120"/>
                                            <el-table-column prop="qty" label="分配数量" min-width="80" />
                                            <el-table-column prop="price" label="门店价格" min-width="140" /> 
                                            <el-table-column prop="storeAmount" label="门店金额" min-width="140" >
                                                <template #default="storeScope">{{storeScope.row.qty*storeScope.row.price}}</template>
                                            </el-table-column>
                                            <el-table-column prop="thirdPrice" label="订单价格" min-width="140" />
                                            <el-table-column prop="thirdAmount" label="订单金额" min-width="140" >
                                                <template #default="storeScope">{{storeScope.row.qty*storeScope.row.thirdPrice}}</template>
                                            </el-table-column>
                                        </el-table>
                                    </el-popover>
                                    <div v-else>未分配</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="文本备注" min-width="160">
                                <template #default="scope">
                                    <div
                                        style="color: #318cf2;text-decoration: underline;cursor: pointer;"
                                        @click="onShowNotes(scope.row.notes)"
                                    >查看内容</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="图片" min-width="160">
                                <template #default="scope">
                                    <sc-upload-multiple
                                        v-model="scope.row.materialImageStrs"
                                        :objName="'Supply/TempMaterial'"
                                        :uploadType="'OSS'"
                                        :bucketName="'jtmc'"
                                        :limit="9"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- <el-row>
                <el-col :span="12" style="margin-left: 10px;">
                    <el-form-item label-width="120px" label="临时物料清单" prop="applyOrderTempItems">
                        <div @click="addTemporary()" class="add-temporary-but">新增临时物料</div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="110px">
                        <el-table
                            :data="entityObj.applyOrderTempItems"
                            border
                            style="width: 100%"
                            show-summary
                        >
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <div
                                        @click="deleteTempRow(scope.$index, scope.row)"
                                        class="del-temp-but"
                                    >移除</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="供货单位" min-width="150" v-if="orgType == 2">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---请选择供货单位---"
                                        v-model="scope.row.purchaseUnityId"
                                        :disabled="purchaseUnityDisabledState"
                                        style="width: 125px"
                                    >
                                        <el-option label="---请选择---" value />
                                        <el-option
                                            v-for="item in optionsPurchaseUnity"
                                            :key="item.purchaseUnityId"
                                            :label="item.purchaseUnityName"
                                            :value="item.purchaseUnityId"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料名称" min-width="130">
                                <template #default="scope">
                                    <el-input v-model="scope.row.materialName" />
                                </template>
                            </el-table-column>
                            <el-table-column label="物料规格" min-width="130">
                                <template #default="scope">
                                    <el-input v-model="scope.row.materialSpecs" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="130">
                                <template #default="scope">
                                    <el-input v-model="scope.row.unitName" />
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="130" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        :min="scope.row.minQty"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="scope">
                                    <el-input
                                        type="textarea"
                                        v-model="scope.row.remarks"
                                        style="width: 100%"
                                        :rows="computedRows(scope.row.remarks)"
                                    />
                                </template>
                            </el-table-column>

                            <el-table-column label="图片" min-width="160">
                                <template #default="scope">
                                    <sc-upload-multiple
                                        v-model="scope.row.materialImageStrs"
                                        :objName="'Supply/TempMaterial'"
                                        :uploadType="'OSS'"
                                        :bucketName="'jtmc'"
                                        :limit="9"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row> -->
            <el-row>
                <el-col :span="24" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="要货备注">
                        <el-collapse v-model="activeNames" style="width: 100%;">
                            <div class="collapse-container">
                                <div class="collapse-header" @click="toggleCollapse">
                                    <span></span>
                                    <div style="display: flex;align-items: center;">
                                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                                        <img
                                            v-if="isCollapsed"
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                                        />
                                        <img
                                            v-else
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                                        />
                                    </div>
                                </div>
                            </div>
                            <div v-show="!isCollapsed" class="collapse-content1">
                                <sc-editor
                                    ref="scRemarks"
                                    v-model="entityObj.remarks"
                                    :height="300"
                                    style="width: 100%;"
                                ></sc-editor>
                            </div>
                        </el-collapse>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="单据金额" prop="totalAmount">
                        <el-input-number
                            v-model="totalAmount"
                            :step="0.01"
                            :precision="2"
                            disabled
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" style="margin-left: 10px;">
                    <el-form-item label-width="120px" label="附件">
                        <sc-upload-file
                            v-model="entityObj.applyFile"
                            :objName="'Supply/ApplyOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(3)"
            >暂 存</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(4)"
            >保 存</el-button>
        </template>
        <!-- 添加物料 -->
        <template>
            <el-dialog
                v-model="materialState"
                title="选择商品"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row style="margin-bottom: 40px;">
                    <sc-material-choice
                        ref="scMaterialChoice"
                        :queryType="'delivery-protocol/distributor-material-item-pages'"
                        :queryList="applyOrderQueryList"
                        @selection-changed="handleSelectionChanged"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
        <!-- 历史要货记录 -->
        <template>
            <el-dialog
                v-model="applyOrderState"
                title="复购"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 540px"
            >
                <el-row style="margin-bottom: 50px;">
                    <sc-apply-order-choice
                        ref="scApplyOrderChoice"
                        :defaultQueryList="applyOrderQueryList"
                    ></sc-apply-order-choice>
                </el-row>
                <template #footer>
                    <el-button @click="applyOrderState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setApplyOrderChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
        <!-- 查看文本备注 -->
        <template>
            <el-dialog
                v-model="notesDialog"
                title="文本备注"
                :width="500"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <div v-html="materialNotes" style="width: 100%"></div>
                </el-row>
                <template #footer>
                    <el-button @click="notesDialog = false">关 闭</el-button>
                </template>
            </el-dialog>
        </template>

        <!-- 分配详情 -->
        <store-detail-dialog
            v-if="storeDetailSave"
            ref="storeDetailDialog"
            @splitOrder="splitOrder"
            @saveOrder="saveOrder"
            @getSupplierDesc="getSupplierDesc"
            @closed="receiveDetailSave = false"
        ></store-detail-dialog>

        <!-- 预览组件 -->
        <el-image-viewer
            v-if="showImage"
            @close="closeViewer"
            :hide-on-click-modal="true"
            :url-list="srcList"
        />
    </full-screen-dialog>
</template>

<script>
import storeDetailDialog from "./storeDetail";
import tool from "@/utils/tool";
export default {
    components: {
        storeDetailDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {},
            orgType: 2,
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            storeDetailSave: false,
            showImage: false,
            materialState: false,
            applyOrderState: false,
            storeQueryList: {},
            applyOrderQueryList: {},
            storeState: false,
            applyOrderItemIndex:0,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            purchaseUnityDisabledState: false,
            purchaseUnityProps: {
                label: "purchaseUnityName",
                value: "purchaseUnityId",
            },
            //验证规则
            rules: {
                applyDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                storeId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                purchaseUnityId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                realName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                mobile: [{ required: true, type: "string", message: "请填写" }],
                address: [
                    { required: true, type: "string", message: "请填写" },
                ],

                purchaseRealName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseMobile: [
                    { required: true, type: "string", message: "请填写" },
                ],

                applyName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                createTime: [
                    { required: true, type: "string", message: "请填写" },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            storeProps: {
                label: "storeOrgName",
                value: "storeId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseUnity: [],
            itemsData: [],
            activeNames: [],
            isCollapsed: true, // 初始状态为收起
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
            notesDialog: false,
            materialNotes: "",
        };
    },
    computed: {
        totalAmount() {
            let materialFee = 0;
            this.entityObj.applyOrderItems.map((p) => {
                p.totalAmount == 0;
                if (p.applyOrderItemType == 0) {
                    p.totalAmount =p.purchases?.reduce((sum, item) => sum + item.qty*item.thirdPrice, 0)??0;
                }
                materialFee += p.totalAmount;
            });
            console.log(materialFee);

            const totalAmount = materialFee ;
            return totalAmount;
        },
    },
    methods: {
        handleSelectionChanged(selectionRows) {
            this.setMaterialChoice();
        },
        //设置备注栏的行数
        computedRows(rowRemarks) {
            // 计算所需的行数
            const lineRow = 10; // 每行的长度
            return rowRemarks?.length / lineRow == 0
                ? 1
                : Math.ceil(rowRemarks?.length / lineRow);
        },
        //图片预览
        handlePreview(row) {
            console.log("row", row.materialImages);
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        //显示=
        async open(mode = "Add") {
            //获取当前店铺信息
            if (mode == "Add" && this.orgType == 2) {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    "store/current"
                );
                if (returnValue.status == 200) {
                    this.entityObj.storeName = returnValue.response.storeName;
                    this.entityObj.storeId = returnValue.response.storeId;
                    this.entityObj.realName = returnValue.response.realName;
                    this.entityObj.mobile = returnValue.response.mobile;
                    this.entityObj.address = returnValue.response.address;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            }
            this.mode = mode;
            this.visible = true;
            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        addTemporary() {
            if (!this.entityObj.applyOrderTempItems) {
                this.entityObj.applyOrderTempItems = [];
            }

            let purchaseUnityId = 0;

            if (
                this.orgType == 1 ||
                (this.entityObj.applyOrderId > 0 && this.entityObj.status != 3)
            ) {
                this.purchaseUnityDisabledState = true;
                purchaseUnityId = this.entityObj.purchaseUnityId;
            } else {
                purchaseUnityId =
                    this.optionsPurchaseUnity &&
                    this.optionsPurchaseUnity.length >= 1
                        ? this.optionsPurchaseUnity[0].purchaseUnityId
                        : 0;
            }

            this.entityObj.applyOrderTempItems.push({
                purchaseUnityId: purchaseUnityId,
                materialTypeId: 0,
                MaterialId: 0,
                MaterialItemId: 0,
                materialCode: "",
                materialName: "",
                materialSpecs: "",
                materialTypeName: "",
                qty: 1,
                totalAmount: 0,
                remarks: "",
                applyOrderItemType: 1,
            });
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        //下单平台(1:pc端)
                        this.entityObj.sourcePlatformType = 1;

                        let data = structuredClone(this.entityObj);
                        if (
                            data.applyOrderTempItems &&
                            data.applyOrderTempItems.length > 0
                        ) {
                            data.applyOrderTempItems.forEach((p) => {
                                p.materialImages = p.materialImageStrs
                                    ? p.materialImageStrs.split(",")
                                    : [];
                            });
                            data.applyOrderTempItems.map((p) =>
                                data.applyOrderItems.push(p)
                            );
                        }

                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "apply-order/create-distributor"
                                    : "apply-order/update",
                                { ...data, status: status }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = {
                otherFee: 0.0,
                applyOrderItems: [],
            };

            this.orgType = tool.data.get("USER_INFO").AccountType;
            this.entityObj.applyName = tool.data.get("USER_INFO").Name;
            this.entityObj.applyDate = this.formatDate(new Date(), 1);
            this.entityObj.createTime = this.formatDate(new Date());

            await this.getPurchaseUnity("purchase-unity/current");

            if (data.applyOrderId > 0) {
                if (
                    this.orgType == 1 ||
                    (data.applyOrderId > 0 && data.status != 3)
                ) {
                    this.purchaseUnityDisabledState = true;
                }

                console.log(this.purchaseUnityDisabledState);

                const materialIds = data.applyOrderItems.map(
                    (p) => p.materialId
                );
                const returnValue = await this.$API.auth.PostProcessApi.post(
                    "delivery-protocol/material-pages",
                    {
                        pageIndex: 1,
                        pageSize: 9999,
                        materialIds: materialIds,
                        storeId: data.storeId,
                    }
                );
                if (returnValue.status == 200) {
                    const materials = returnValue.response.data;
                    this.entityObj = {
                        applyOrderId: data.applyOrderId,
                        ...data,
                        stores: {
                            storeId: data.storeId,
                            storeName: data.storeName,
                        },
                        applyOrderItems: [],
                        applyOrderTempItems: [],
                    };
                    data.applyOrderItems.map((p) => {
                        const material = materials.find(
                            (t) =>
                                t.materialId == p.materialId &&
                                t.purchaseUnityId == p.purchaseUnityId
                        );
                        this.entityObj.applyOrderItems.push({
                            purchaseUnityId: p.purchaseUnityId,
                            materialId: material.materialId,
                            materialCode: material.materialCode,
                            materialSimpCode: material.materialSimpCode,
                            materialName: material.materialName,
                            materialSpecs: material.materialSpecs,
                            materialTypeId: material.materialTypeId,
                            materialTypeName: material.materialTypeName,
                            materialImages: material.materialImages,
                            //price: p.price,
                            qty: p.qty,
                            totalAmount: p.totalAmount,
                            remarks: p.remarks,
                            materialItemId: p.materialItemId,
                            materialItems: material.materialItems,
                            applyOrderItemType: 0,
                        });
                    });
                    data.applyOrderItemTemps.map((p) => {
                        this.entityObj.applyOrderTempItems.push({
                            purchaseUnityId: p.purchaseUnityId,
                            materialTypeId: 0,
                            MaterialId: 0,
                            MaterialItemId: 0,
                            materialCode: "",
                            materialName: p.materialName,
                            unitName: p.unitName,
                            materialImages: p.materialImages,
                            materialImageStrs: p.materialImages.join(","),
                            materialSpecs: p.materialSpecs,
                            materialTypeName: "",
                            qty: p.qty,
                            totalAmount: 0,
                            remarks: p.remarks,
                            applyOrderItemType: 1,
                        });
                    });
                }
            }

            this.queryList = {};
            this.handleSearch();
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            if (this.orgType == 2) {
                try {
                    var returnValue = await this.$API.auth.GetProcessApi.get(
                        "store/current-purchaseUnity",
                        {}
                    );
                    if (returnValue.status == 200) {
                        this.optionsPurchaseUnity = returnValue.response;
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },
        async getPurchaseUnity(url) {
            //采购单位列表
            var returnValue = await this.$API.auth.GetProcessApi.get(url);
            if (returnValue.status == 200) {
                this.entityObj.purchaseUnityId =
                    returnValue.response.purchaseUnityId;
                this.entityObj.purchaseUnityName =
                    returnValue.response.purchaseUnityName;
                this.entityObj.purchaseRealName = returnValue.response.realName;
                this.entityObj.purchaseMobile = returnValue.response.mobile;
                this.entityObj.purchaseAddress = returnValue.response.address;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        async supplierSelectProcess(rowData) {
            this.entityObj.supplier = {};
            if (rowData) {
                this.entityObj.supplier = {
                    supplierId: rowData.supplierId,
                    supplierName: rowData.supplierName,
                };
            }
            console.log(this.entityObj.supplier);
        },
        //选择物料
        addMaterial() {
            this.materialState = true;
            this.$nextTick(() => {
                this.$refs.scMaterialChoice.opBindData();
            });
        },
        //添加物料
        setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                this.entityObj.applyOrderItems.push({
                    purchaseUnityId: p.purchaseUnityId,
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSimpCode: p.materialSimpCode,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    materialImages: p.materialImages,
                    unitName: p.unitName,
                    unitCode: p.unitCode,
                    qty: p.minApplyQty ?? 1,
                    minQty: p.minApplyQty ?? 1,
                    totalAmount: 0,
                    remarks: "",
                    notes: p.notes,
                    materialItemId: p.materialItemId,
                    applyOrderItemType: 0,
                    stores: p.distributorStoreDeliveryPrice,
                });
            });
            this.materialState = false;
            this.queryList = {};
            this.handleSearch();
        },
        //删除物料
        deleteRow(index) {
            this.entityObj.applyOrderItems.splice(index, 1);
        },
        //分配门店
        opStoreRow(index,data) {
            this.applyOrderItemIndex=index;
            this.storeDetailSave = true;
            this.$nextTick(() => {
                this.$refs.storeDetailDialog.setData(data);
                this.$refs.storeDetailDialog.open("Add");
            });
        },
        //保存分配门店
        saveOrder(row){
            this.entityObj.applyOrderItems[this.applyOrderItemIndex].purchases=row.purchases;
            this.handleSearch();
        },
        //获取门店信息
        getStoreDesc(row) {
            if(!row.purchases||row.purchases.length==0){
                return "未分配";
            }

            return row.purchases
                .map((store) => `${store.storeName}/${store.qty}`)
                .join(", ");
        },
        deleteTempRow(index) {
            this.entityObj.applyOrderTempItems.splice(index, 1);
        },
        handleSearch() {
            this.itemsData = this.entityObj.applyOrderItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                this.itemsData = this.itemsData.filter((item) => {
                    return (
                        item.materialCode.includes(
                            this.queryList.materialCode
                        ) 
                    );
                });
            }

            if (this.queryList.materialName) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
        },
        async addApplyOrder() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            // if (!this.entityObj.purchaseUnityId) {
            //     this.$message.error("请先选择采购单位");
            //     return;
            // }

            // 查询是否有历史要货记录，有的话默认最近一天的记录
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "apply-order/applyOrder-last-dates",
                { storeId: this.entityObj.storeId }
            );
            // if(!returnValue.response){
            //     this.$message.error("暂无历史要货记录");
            //     return;
            // }
            this.applyOrderState = true;
            this.applyOrderQueryList = {
                applyDates: returnValue.response,
                storeId: this.entityObj.storeId,
            };
            if (
                this.orgType == 1 ||
                (this.entityObj.applyOrderId > 0 && this.entityObj.status != 3)
            ) {
                this.applyOrderQueryList = {
                    applyDates: returnValue.response,
                    storeId: this.entityObj.storeId,
                    purchaseUnityId: this.entityObj.purchaseUnityId,
                };
            }
            this.$nextTick(() => {
                this.$refs.scApplyOrderChoice.opBindData();
            });
        },
        async setApplyOrderChoice() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            // if (!this.entityObj.purchaseUnityId) {
            //     this.$message.error("请先选择采购单位");
            //     return;
            // }

            let applyOrders = this.$refs.scApplyOrderChoice.selectionRows;
            let materialIds = [];
            // applyOrders.map((t) =>
            //     t.applyOrderItems.map((p) => {
            //         materialIds.push(p.materialId);
            //     })
            // );

            applyOrders.map((p) => {
                materialIds.push(p.materialId);
            });
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "delivery-protocol/material-pages",
                {
                    pageIndex: 1,
                    pageSize: 9999,
                    storeId: this.entityObj.storeId,
                    materialIds: materialIds,
                }
            );
            if (returnValue.status == 200) {
                const materials = returnValue.response.data;
                // applyOrders.map((t) =>
                //     t.applyOrderItems.map((p) => {
                //         const material = materials.find(
                //             (z) =>
                //                 z.materialId == p.materialId &&
                //                 z.purchaseUnityId == p.purchaseUnityId
                //         );

                //         if (material) {
                //             this.entityObj.applyOrderItems.push({
                //                 purchaseUnityId: p.purchaseUnityId,
                //                 materialId: material.materialId,
                //                 materialCode: material.materialCode,
                //                 materialName: material.materialName,
                //                 materialSpecs: material.materialSpecs,
                //                 materialSimpCode: material.materialSimpCode,
                //                 materialTypeId: material.materialTypeId,
                //                 materialTypeName: material.materialTypeName,
                //                 //price: p.price,
                //                 qty: p.qty,
                //                 //totalAmount: p.totalAmount,
                //                 remarks: p.remarks,
                //                 materialItemId: p.materialItemId,
                //                 materialItems: material.materialItems,
                //                 applyOrderItemType: 0,
                //             });
                //         }
                //     })
                // );
                console.log("applyOrders", applyOrders);
                applyOrders.map((p) => {
                    if (p.applyOrderItemType == 0) {
                        const material = materials.find(
                            (z) =>
                                z.materialId == p.materialId &&
                                z.purchaseUnityId == p.purchaseUnityId
                        );

                        if (material) {
                            const materialItem =
                                material.materialItems.length > 0
                                    ? material.materialItems[0]
                                    : [];
                            this.entityObj.applyOrderItems.push({
                                purchaseUnityId: p.purchaseUnityId,
                                materialId: material.materialId,
                                materialCode: material.materialCode,
                                materialName: material.materialName,
                                materialSpecs: material.materialSpecs,
                                materialSimpCode: material.materialSimpCode,
                                materialTypeId: material.materialTypeId,
                                materialTypeName: material.materialTypeName,
                                //price: p.price,
                                qty:
                                    p.qty >= materialItem?.minApplyQty
                                        ? p.qty
                                        : materialItem?.minApplyQty,
                                minQty: materialItem?.minApplyQty
                                    ? materialItem?.minApplyQty
                                    : 1,
                                //totalAmount: p.totalAmount,
                                remarks: p.remarks,
                                materialItemId: p.materialItemId,
                                materialItems: material.materialItems,
                                applyOrderItemType: 0,
                            });
                        }
                    } else {
                        if (
                            !this.entityObj.applyOrderTempItems ||
                            this.entityObj.applyOrderTempItems.length == 0
                        ) {
                            this.entityObj.applyOrderTempItems = [];
                        }

                        this.entityObj.applyOrderTempItems.push({
                            purchaseUnityId: p.purchaseUnityId,
                            materialTypeId: 0,
                            MaterialId: 0,
                            MaterialItemId: 0,
                            materialCode: "",
                            materialName: p.materialName,
                            unitName: p.unitName,
                            materialSpecs: p.materialSpecs,
                            materialTypeName: "",
                            qty: p.qty,
                            totalAmount: 0,
                            remarks: p.remarks,
                            applyOrderItemType: 1,
                        });
                    }
                });
                console.log(1111);
                this.applyOrderState = false;
                this.queryList = {};
                this.handleSearch();
            }
        },
        purchaseUnityChange(value) {
            this.entityObj.purchaseRealName = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).realName;
            this.entityObj.purchaseMobile = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).mobile;
        },
        storeSelectProcess(rowData) {
            if (
                this.entityObj.applyOrderItems &&
                this.entityObj.applyOrderItems.length > 0
            ) {
                this.$confirm("是否修改要货门店,要货清单会被清空？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.entityObj.applyOrderItems = [];
                        this.handleSearch();
                        this.setStore(rowData);
                    })
                    .catch(() => {});
            }
            this.setStore(rowData);
        },
        setStore(rowData) {
            this.entityObj.store = rowData;
            this.entityObj.storeName = rowData.storeName;
            this.entityObj.storeOrgType = rowData.storeOrgType;
            this.entityObj.storeId = rowData.storeId;
            this.entityObj.realName = rowData.realName;
            this.entityObj.mobile = rowData.mobile;
            this.entityObj.address = rowData.address;
        },
        async purchaseUnitySelectProcess(rowData) {
            if (
                this.entityObj.applyOrderItems &&
                this.entityObj.applyOrderItems.length > 0
            ) {
                this.$confirm("是否修改采购单位,要货清单会被清空？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.entityObj.applyOrderItems = [];
                        this.handleSearch();
                        this.setPurchaseUnity(rowData);
                    })
                    .catch(() => {});
            }
            this.setPurchaseUnity(rowData);
        },
        setPurchaseUnity(rowData) {
            if (rowData) {
                this.entityObj.purchaseUnityId = rowData.purchaseUnityId;
                this.entityObj.purchaseUnityName = rowData.purchaseUnityName;
                this.entityObj.realName = rowData.realName;
                this.entityObj.mobile = rowData.mobile;
                this.entityObj.address = rowData.address;
                this.entityObj.purchaseUnitys = {
                    purchaseUnityId: rowData.purchaseUnityId,
                    purchaseUnityName: rowData.purchaseUnityName,
                };
            }
        },
        resetSearch() {
            this.queryList = {};
        },
        formatDate(date, type = 0) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return type == 0
                ? `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
                : `${year}-${month}-${day}`;
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        //显示文本备注
        onShowNotes(notes) {
            console.log("显示文本备注", notes);
            this.notesDialog = true;
            this.materialNotes = notes;
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        await this.initOptions();
    },
};
</script>

<style lang="scss" scoped>
.add-material-but {
    text-align: center;
    width: 80px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.add-order-but {
    margin-left: 10px;
    text-align: center;
    width: 160px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.add-temporary-but {
    text-align: center;
    width: 100px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.del-temp-but {
    text-align: center;
    padding: 0px 5px;
    height: 24px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.w25pr30 {
    width: 25%;
    padding-right: 30px;
}
.w25 {
    width: 25%;
}

::v-deep .el-form-item__label {
    width: 100px !important;
    justify-content: flex-start;
}

.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 5px;
    padding-left: 0;
    font-weight: bold;
    font-size: 12px;
}
.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
</style>

<style scoped>
/deep/ .el-upload--picture-card {
    width: 50px;
    height: 50px;
}
/deep/ .el-upload {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-table .info-row > td {
    background: #e4e7ed;
    user-select: none; /* 禁用文本选择 */
    pointer-events: none; /* 禁用鼠标事件 */
}
</style>
